package com.colin.juc.threadlocal;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Colin on 2020/4/5 13:32
 * email: colinzhaodong@gmail.com
 * desc: //1000个打印日期的任务,用线程池来执行,加锁解决线程安全,弊端1000个线程日期格式化时需要排队
 *
 * @author zhaod
 */
public class ThreadLocalUsageFifth {
	public static ExecutorService threadPool = Executors.newFixedThreadPool(10);
	static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	static Set set = Collections.synchronizedSet(new HashSet(1001));
	public static void main(String[] args) throws InterruptedException {
		for (int i = 0; i < 1000; i++) {
			int finalI = i;
			threadPool.submit(new Runnable() {
				@Override
				public void run() {
					String date = new ThreadLocalUsageFifth().date(finalI);
					set.add(date);
				}
			});
		}
		Thread.sleep(1000);
		System.out.println(set.size());
		threadPool.shutdown();
	}

	public String date(int seconds) {
		//参数的单位是毫秒，从1970.1.1 00:00:00 GMT计时
		Date date = new Date(1000 * seconds);
		String format = "";
		synchronized (ThreadLocalUsageFifth.class) {
			format = dateFormat.format(date);
		}
		return format;
	}
}
